package com.zoweunion.mechanic.service.app.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.dao.app.TSSsInsuranceDao;
import com.zoweunion.mechanic.dao.app.TSSsInsuranceDetailDao;
import com.zoweunion.mechanic.entity.TSSsInsuranceDetailEntity;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.service.app.TSSsInsuranceService;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.SmsUtil;
import com.zoweunion.mechanic.util.constants.Constants;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.zoweunion.mechanic.entity.TSSsInsuranceEntity;
import org.springframework.transaction.annotation.Transactional;


@Service("tSSsInsuranceService")
public class TSSsInsuranceServiceImpl extends ServiceImpl<TSSsInsuranceDao, TSSsInsuranceEntity> implements TSSsInsuranceService {

    @Autowired
    private TSSsInsuranceDao tSSsInsuranceDao;
    @Autowired
    private TSSsInsuranceDetailDao tsSsInsuranceDetailDao;

    /**
     * 电商ID
     */
    private final String EBusinessID = "1580543";
    /**
     * 电商加密私钥，快递鸟提供，注意保管，不要泄漏
     */
    private final String AppKey = "366fdb53-0c24-4de7-b7be-9556ee9dd8ca";
    /**
     * 及时查询和单号识别url
     */
    private final String ReqURL = "http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";



    @Override
    public PageInfo queryPage(Map<String, Object> map,User currentUser)  {

        Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(map.get("currentPage").toString());
        map.put("currentUser",currentUser.getId());
        PageHelper.startPage(currentPage, pageSize);
        List<TSSsInsuranceEntity> mapList = tSSsInsuranceDao.queryPage(map);
        PageInfo<TSSsInsuranceEntity> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    /**
     * 修改
     * @param params
     */
    @Override
    public Long updateInsurance(TSSsInsuranceEntity params, User currentUser) {
        params.setRefuseReason(null);
        params.setOrderStatus(Constants.InsuranceEnum.WAIT_PRICE.getCode());
        tSSsInsuranceDao.updateById(params);
        //Integer orderStatus = Constants.InsuranceEnum.WAIT_PRICE.getCode();
        //insertDetail(params, currentUser, orderStatus);
        return params.getId();
    }

    /**
     * 新增
     * @param params
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveInsurance(TSSsInsuranceEntity params, User currentUser) throws MyException{
        //是否有待报价的车
        int isNowApply = tSSsInsuranceDao.isNowApply(params.getCarEngineNumber());
        if(isNowApply>0){
            throw new MyException(Constants.CODE_HANDEL_FAILED,"该发动机号车辆正在申请，请勿重复申请");
        }
        Date date = new Date();
        Integer orderStatus = Constants.InsuranceEnum.WAIT_PRICE.getCode();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderId = "C"+sdf1.format(new Date())+(int) ((Math.random()*9+1)*100000);
        if(!"1".equals(params.getInsuranceServerId())){
            params.setInsuranceServerId("2");
        }
        TSSsInsuranceEntity build = params.toBuilder()
                .orderId(orderId)
                .createTime(date)
                .createUser(currentUser.getId())
                .updateTime(date)
                .updateUser(currentUser.getId())
                .sId(currentUser.getS_id())
                .orderStatus(orderStatus)
                .payStatus(0)
                .deleteFlag(0)
                .qrCodeApplyStatus(0)
                .build();
        if(StringUtils.isEmpty(params.getInsuredMan())){
            build = build.toBuilder().insuredMan(params.getBuyerName()).build();
        }
        tSSsInsuranceDao.insert(build);
        //insertDetail(build, currentUser, orderStatus);

        if(Constants.InsuranceEnum.WAIT_PRICE.getCode().equals(orderStatus)){
            SmsUtil.sendSms(Constants.INSURANCE_PHONE, "【机修狮】提醒：您有一条新的保险订单需要报价，请您及时处理！");
        }
        return build.getId();
    }

    private void insertDetail(TSSsInsuranceEntity build, User currentUser,Integer orderStatus) {
        Date date = new Date();
        TSSsInsuranceDetailEntity detail = new TSSsInsuranceDetailEntity();
        String statusText = Constants.InsuranceEnum.getRoleName(orderStatus);
        detail.setCreateTime(date);
        detail.setCreateUser(currentUser.getId());
        detail.setUpdateTime(date);
        detail.setUpdateUser(currentUser.getId());
        detail.setDeleteFlag(0);
        detail.setOrderId(build.getId());
        detail.setOrderStatus(orderStatus);
        detail.setStatusText(statusText);
        tsSsInsuranceDetailDao.insert(detail);
        if(orderStatus==Constants.InsuranceEnum.WAIT_PRICE.getCode()||orderStatus==Constants.InsuranceEnum.WAIT_PRICE_PASS.getCode()){
            String text = Constants.InsuranceEnum.WAIT_PRICE_FAIL.getName();
            tSSsInsuranceDao.removeDelete(build.getId(),text);
        }
    }

    @Override
    public TSSsInsuranceEntity getInsuranceDetail(String id) {
        TSSsInsuranceEntity info = tSSsInsuranceDao.getById(id);
//        List<TSSsInsuranceDetailEntity> detailList = tSSsInsuranceDao.getDetailList(id);
//        info.setDetailList(detailList);
        return info;
    }

    @Override
    public void updateStatus(TSSsInsuranceEntity params, User currentUser) {
        params.setUpdateUser(currentUser.getId());
        params.setUpdateTime(new Date());
        Integer orderStatus = params.getOrderStatus();
        Long id = params.getId();
        tSSsInsuranceDao.updateStatus(params);
        if(Constants.InsuranceEnum.USER_CONFIRM.getCode().equals(orderStatus)){
            String extraMapString = tSSsInsuranceDao.getExtra(20,id);
            Map<String,Object> extraMap = (Map<String,Object>)JSON.parse(extraMapString);
            extraMap.put("orderStatus",orderStatus);
            String extraParams = JSONObject.toJSONStringWithDateFormat(extraMap, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
            tSSsInsuranceDao.updateExtra(20,id,extraParams);
        }
//        Integer orderStatus = params.getOrderStatus();
//        if(Constants.InsuranceEnum.USER_CONFIRM.getCode().equals(orderStatus)){
//            SmsUtil.sendSms("18438610359", "用户已付款，请及时进行审核");
//        }

//        if(orderStatus != null){
//            this.insertDetail(params,currentUser,orderStatus);
//        }
    }

    @Override
    public Map<String,Object> getPayStatus(Map<String, Object> params, User currentUser) {
        String orderId = null;
        Integer orderType = null;
        if(params.get("orderId")!=null){
            orderId = params.get("orderId").toString();
        }
        if(params.get("orderType")!=null){
            orderType = Integer.parseInt(params.get("orderType").toString());
        }

        return tSSsInsuranceDao.getPayStatus(orderId,orderType);
    }

    @Override
    public ResponseBean updateExpress(TSSsInsuranceEntity params,User currentUser) {
        String expNo = params.getExpressNum();
        Map<String, Object> resultMap=null;
        try {
            String information = this.getOrderTracesTypeByJson(expNo);
            resultMap = JSON.parseObject(information);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (params.getPhoneShort()!=null){
            Map<String, Object> map = new HashMap<>();
            map.put("expNo",params.getExpressNum());
            Map<String, Object> shipperCodeMap = this.judgeInformation(map);
            List<Map<String, Object>> shippers = (List<Map<String, Object>>) shipperCodeMap.get("Shippers");
            if (shippers == null || shippers.size() == 0) {
                return new ResponseBean(Constants.CODE_HANDEL_FAILED, "暂无物流信息，请检查单号是否正确", null);
            }
            params.setExpressNo("SF");
            params.setExpressName("顺丰快递");
        }else {
            List<Map<String, Object>> shippers = (List<Map<String, Object>>)resultMap.get("Shippers");
            if (shippers != null) {
                for (Map<String, Object> shipperMap : shippers) {
                    if (shipperMap.get("ShipperCode") != null) {
                        // 快递公司编码
                        params.setExpressNo(shipperMap.get("ShipperCode").toString());
                        params.setExpressName(shipperMap.get("ShipperName").toString());
                    }
                }
            }
            if (shippers == null || shippers.size() == 0) {
                return new ResponseBean(Constants.CODE_HANDEL_FAILED, "暂无物流信息，请检查单号是否正确", null);
            }
        }
        tSSsInsuranceDao.updateExpress(params);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", params.getId());
    }
    /**
     * Json方式 查询订单物流轨迹
     *
     * @param expCode 所属公司 如SF
     * @param expNo   快递编号
     * @return
     * @throws Exception
     */
    public String getOrderTracesByJson(String expCode, String expNo) throws Exception {
        String requestData = String.format("{\"OrderCode\":\"\",\"ShipperCode\":\"%s\",\"LogisticCode\":\"%s\"}", expCode, expNo);
        Map<String, String> params = this.createSystemParam(requestData, "1002");
        return sendPost(ReqURL, params);
    }

    private Map<String, String> createSystemParam(String requestData, String requestType) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("RequestData", urlEncoder(requestData, "UTF-8"));
        params.put("EBusinessID", EBusinessID);
        params.put("RequestType", requestType);
        String dataSign = encrypt(requestData, AppKey, "UTF-8");
        params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
        params.put("DataType", "2");
        return params;
    }


    private String urlEncoder(String str, String charset) throws UnsupportedEncodingException {
        return URLEncoder.encode(str, charset);
    }

    private String encrypt(String content, String keyValue, String charset) throws UnsupportedEncodingException, Exception {
        if (keyValue != null) {
            return base64(MD5(content + keyValue, charset), charset);
        }
        return base64(MD5(content, charset), charset);
    }

    private String MD5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }

    private String base64(String str, String charset) throws UnsupportedEncodingException {
        return base64Encode(str.getBytes(charset));
    }

    private static String base64Encode(byte[] data) {
        StringBuilder sb = new StringBuilder();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;
        while (i < len) {
            b1 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                sb.append("==");
                break;
            }
            b2 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                sb.append("=");
                break;
            }
            b3 = data[i++] & 0xff;
            sb.append(base64EncodeChars[b1 >>> 2]);
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
            sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
            sb.append(base64EncodeChars[b3 & 0x3f]);
        }
        return sb.toString();
    }

    private static char[] base64EncodeChars = new char[]{
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/'};


    /**
     * Json方式 查询订单物流轨迹
     *
     * @param expCode      所属公司 如SF
     * @param expNo        快递编号
     * @param customerName 如果是顺丰则是 寄件人或者收件人手机号码后4位
     * @return
     * @throws Exception
     */
    public String getOrderTracesByJson(String expCode, String expNo, String customerName) throws Exception {
        String requestData = String.format("{\"OrderCode\":\"\",\"ShipperCode\":\"%s\",\"LogisticCode\":\"%s\",\"CustomerName\":\"%s\"}", expCode, expNo, customerName);
        Map<String, String> params = this.createSystemParam(requestData, "1002");
        return sendPost(ReqURL, params);
    }

    private String sendPost(String url, Map<String, String> params) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            // 发送请求参数
            if (params != null) {
                StringBuilder param = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (param.length() > 0) {
                        param.append("&");
                    }
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                }
                out.write(param.toString());
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

    public String getOrderTracesTypeByJson(String expNo) throws Exception {
        String requestData = String.format("{\"LogisticCode\":\"%s\"}", expNo);
        Map<String, String> params = this.createSystemParam(requestData, "2002");
        return sendPost(ReqURL, params);
    }

    public Map<String, Object> judgeInformation(Map<String, Object> reqMap) {
        Map<String, Object> resultMap = null;
        String expNo = (String) reqMap.get("expNo");
        try {
            String information = this.getOrderTracesTypeByJson(expNo);
            resultMap = JSON.parseObject(information);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

//    @Override
//    public TSSsInsuranceEntity logisticsExpress(Map<String, Object> reqMap) {
//        String id = reqMap.get("id").toString();
//        TSSsInsuranceEntity insuranceOrder = tSSsInsuranceDao.selectInsuranceOrderInfo(id);
//        String expCode = insuranceOrder.getExpressNo();//快递公司
//        String expNo = insuranceOrder.getExpressNum();
//        try {
//            // 查询物流信息
//            String information;
//            if ("SF".equals(expCode)) {
//                String customerName = insuranceOrder.getPhoneShort().toString();
//                information = this.getOrderTracesByJson(expCode, expNo, customerName);
//            } else {
//                information = this.getOrderTracesByJson(expCode, expNo);
//            }
//            Map<String, Object> informationMap = (Map<String, Object>) JSON.parse(information);
//            if (informationMap.containsKey("Reason")) {
//                informationMap.put("message", informationMap.get("Reason").toString());
//            }
//            informationMap.remove("EBusinessID");
//            insuranceOrder.setExpress(informationMap);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return insuranceOrder;
//    }
}
